<template>
  <div class="page-container">
    <!-- 搜索表单 -->
    <div class="search-form" ref="searchForm">
      <el-form ref="refForm" :model="formParams" :inline="true">
        <el-form-item prop="keyword">
          <template #label>
            <span class="serach-label">
              {{ $t('common.field.keyword', '关键字') }}：
            </span>
          </template>
          <el-input
            style="width: 220px"
            v-model="formParams.keyword"
            :placeholder="$p('common.field.keyword', '关键字')"
          />
        </el-form-item>

        <el-form-item prop="extension">
          <template #label>
            <span class="serach-label">
              {{ $t('menu.admin.file.field.extension', '扩展名') }}：
            </span>
          </template>
          <el-input
            style="width: 220px"
            v-model="formParams.extension"
            :placeholder="$p('menu.admin.file.field.extension', '扩展名')"
          />
        </el-form-item>

        <el-form-item prop="createTime">
          <template #label>
            <span class="serach-label">
              {{ $t('common.field.create_time', '创建时间') }}：
            </span>
          </template>
          <div style="width: 220px">
            <el-date-picker
              v-model="formParams.createTime"
              type="daterange"
              value-format="YYYY-MM-DD"
              :start-placeholder="
                $t('common.message.placeholder.date_start', '开始日期')
              "
              :end-placeholder="
                $t('common.message.placeholder.date_end', '结束日期')
              "
            />
          </div>
        </el-form-item>
        <el-form-item>
          <div style="margin-left: 10px">
            <el-button type="primary" icon="Search" @click="loadFiles">
              {{ $t('common.action.search', '查询') }}
            </el-button>
            <el-button type="info" icon="Refresh" @click="reset">
              {{ $t('common.action.reset', '重置') }}
            </el-button>
            <el-button
              type="success"
              icon="Upload"
              @click="handleUpload"
              v-hasPerm="['admin:file:add']"
            >
              {{ $t('common.action.upload', '上传') }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 文件 Grid -->
    <div class="grid-container" :style="{ height: gridHeight + 'px' }">
      <!-- 如果有文件 -->
      <template v-if="files.length > 0">
        <el-card
          class="card-container"
          shadow="never"
          v-for="(file, index) in files"
          :key="index"
        >
          <el-image
            v-if="file.mime.includes('image')"
            lazy
            class="image-container"
            fit="cover"
            :src="file.url"
            :alt="file.name"
          ></el-image>
          <div class="image-container font-image" v-else>
            {{ file.extension }}
          </div>

          <template #footer>
            <el-text class="title" truncated>
              {{ file.name }}
            </el-text>
          </template>
          <div class="overlay">
            <!-- 上传按钮 -->
            <el-icon
              class="icon mr-6"
              color="white"
              size="20"
              v-hasPerm="['admin:file:download']"
              @click="handleDownload(file.url, file.name)"
            >
              <Download />
            </el-icon>

            <!-- 预览按钮 -->
            <el-icon
              class="icon mr-6"
              color="white"
              size="20"
              v-if="file.mime.includes('image')"
            >
              <View @click="showPreview(index)" />
            </el-icon>

            <!-- 修改文件名 -->
            <el-icon
              class="icon mr-6"
              color="white"
              size="20"
              v-hasPerm="['admin:file:update']"
            >
              <Edit @click="changeOriginName(file)" />
            </el-icon>

            <!-- 删除文件 -->
            <el-icon
              class="icon"
              color="white"
              size="20"
              v-hasPerm="['admin:file:delete']"
            >
              <Delete @click="deleteFile(file)" />
            </el-icon>
          </div>
        </el-card>
      </template>
      <!-- 如果没有 -->
      <div v-else class="empty-state">
        <el-empty
          :description="$t('common.message.info.empty', '暂无数据！')"
        />
      </div>
    </div>
    <!-- 分页 -->
    <div class="page-container" ref="pageContainer">
      <vxe-pager
        v-model:current-page="pageParams.currentPage"
        v-model:page-size="pageParams.pageSize"
        :total="pageParams.total"
        @page-change="pageChangeEvent"
      />
    </div>
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="viewVisible"
      :zoom-rate="1.2"
      :initial-index="initialIndex"
      :url-list="viewFileList"
      @close="closePreview"
    />
    <!-- 文件上传 -->
    <ra-upload
      ref="refRaUpload"
      :multiple="true"
      :onlyImage="false"
      @reload="loadFiles"
    ></ra-upload>
  </div>
</template>

<script setup>
defineOptions({
  // 组件名称
  name: 'AdminFile',
  // 阻止透传非 props 属性
  inheritAttrs: false,
});

import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import AdminFileAPI from '@/api/admin/admin/file';

// 载入效果
const loading = ref(false);
// 表单
const refForm = ref();
// 查询到的文件列表
const files = ref([]);

// 搜索栏
const searchForm = ref();
// grid高度
const gridHeight = computed(() => {
  if (searchForm.value) {
    console.log('searchForm.value.offsetHeight', searchForm.value.offsetHeight);
    return window.innerHeight - 162 - searchForm.value.offsetHeight;
  }
});

// 查询参数
const formParams = reactive({
  keyword: '',
  extension: '',
  createTime: '',
});
// 搜索参数
const pageParams = reactive({
  currentPage: 1,
  pageSize: 20,
  total: null,
});

// 复位查询
const reset = () => {
  refForm.value.resetFields();
};

// 数据加载
const loadFiles = async () => {
  try {
    formParams.current_page = pageParams.currentPage;
    formParams.page_size = pageParams.pageSize;
    const { data: response } = await AdminFileAPI.index(formParams);
    const {
      current_page: currentPage,
      per_page: pageSize,
      total,
      data,
    } = response;
    Object.assign(pageParams, { currentPage, pageSize, total });
    files.value = data;
  } catch (error) {
    console.error('Failed to fetch files:', error);
  }
};

/**
 * 分页变化
 */
const pageChangeEvent = (e) => {
  pageParams.currentPage = e.currentPage;
  pageParams.pageSize = e.pageSize;
  loadFiles();
};

/**
 * 图片预览
 */
const viewVisible = ref(false);
const initialIndex = ref(0);
const viewFileList = ref();
const showPreview = (index) => {
  initialIndex.value = index;
  viewFileList.value = files.value.map((file) => file.url);
  viewVisible.value = true;
};
const closePreview = () => {
  viewVisible.value = false;
};

/**
 * 文件上传
 */
const refRaUpload = ref();
const handleUpload = () => {
  refRaUpload.value.show();
};

/**
 * 下载
 */
const handleDownload = (url, fileName) => {
  let fileUrl = '';
  // 获取当前页面的协议和域名
  const currentOrigin = window.location.origin;
  // 检查URL是否已经是完整的（包含协议）
  if (/^(https?:\/\/)/i.test(url)) {
    fileUrl = url; // 如果是完整的URL，直接返回
  } else {
    fileUrl = currentOrigin + url;
  }
  AdminFileAPI.download(fileUrl, fileName);
};

/**
 * 修改源文件名
 */
const changeOriginName = (file) => {
  ElMessageBox.prompt(
    $t('common.message.info.rename', '请输入新的名称'),
    $t('common.title.rename', '重命名'),
    {
      inputValue: file.name,
    },
  )
    .then(({ value }) => {
      AdminFileAPI.update({ id: file.id, name: value }).then(() => {
        ElMessage({
          type: 'success',
          message: $t('common.message.success.general', '{action} 成功！', {
            action: $t('common.action.rename', '重命名'),
          }),
        });
        loadFiles();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: $t('common.message.cancel.general', '取消 {action} 操作！', {
          action: $t('common.action.rename', '重命名'),
        }),
      });
    });
};

/**
 * 删除文件
 */
const deleteFile = (file) => {
  ElMessageBox.confirm(
    $t('common.message.confirm.general', '确定要执行 {action} 操作吗！', {
      action: $t('common.action.delete', '删除'),
    }),
    $t('common.title.delete', '删除'),
    {
      type: 'warning',
    },
  )
    .then(() => {
      AdminFileAPI.delete({ id: [file.id] }).then(() => {
        ElMessage({
          type: 'success',
          message: $t('common.message.success.general', '{action} 成功！', {
            action: $t('common.action.delete', '删除'),
          }),
        });
        loadFiles();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: $t('common.message.cancel.general', '取消 {action} 操作！', {
          action: $t('common.action.delete', '删除'),
        }),
      });
    });
};

onMounted(() => {
  // 加载初始数据
  loadFiles();
});
</script>

<style lang="scss" scoped>
.page-container {
  width: 100%;
  padding: 5px;
  border-radius: 4px;
  background-color: var(--el-bg-color-overlay);
  .search-form {
    display: flex;
    flex-wrap: wrap;
    margin: 5px 10px 0px 10px;
    width: 100%;
    justify-content: flex-start;

    @media (max-width: 768px) {
      display: none; /* 当屏幕宽度小于等于 768px 时隐藏表单 */
    }
  }
  .grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
    gap: 10px;
    padding: 5px;
    // background-color: #fff;
    overflow-y: auto; /* 只允许垂直滚动 */
    overflow-x: hidden; /* 隐藏水平滚动条 */
    align-items: start; /* 内容靠顶部对齐 */
    grid-auto-rows: 220px; /* 固定行高 */
  }
  .card-container {
    position: relative;
    cursor: pointer;
    height: 220px;
    position: relative;
    text-align: center;
    // background-color: #fff;
    width: 100%;
    .image-container {
      height: 150px;
      width: 150px;
    }
    .font-image {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .title {
      font-size: 12px;
      // color: #333;
      text-align: center;
    }
    .overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.223); /* 半透明背景色 */
      display: flex;
      justify-content: center;
      align-items: flex-end;
      padding-bottom: 20px;
      opacity: 0;
      transition: opacity 0.3s;
      z-index: 10; /* 确保覆盖层在最上层 */
    }

    &:hover .overlay {
      opacity: 1;
    }

    .icon {
      color: white;
      transition: color 0.3s;

      &:hover {
        color: #61ff7e; /* 悬停时的颜色 */
      }
    }
  }
  .empty-state {
    display: flex;
    flex-grow: 1;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    grid-column: 1 / -1; /* 占据所有列 */
    grid-row: 1 / -1; /* 占据所有行 */
  }
  .serach-label {
    font-weight: bold;
  }
}
</style>
